const util = require('./../../utils/selectColorUtil')
const app = getApp();
let colorPickerCtx = {};
let sliderCtx = {};
let _this = null;
Component({
  properties: {
    moduleText: { // 属性名
      type: String,
      value: ''
    },
  },
  data: {
    pickColor: null,
    raduis: 550, //这里最大为750rpx铺满屏幕
    valueWidthOrHerght: 300
  },
  attached: function () {

  },
  ready() {
    _this = this
    colorPickerCtx = wx.createCanvasContext('colorPicker', this);
    colorPickerCtx.fillStyle = 'rgb(255, 255, 255)';
    sliderCtx = wx.createCanvasContext('colorPickerSlider', this);
    let isInit = true;

    this.createSelectorQuery().select('#colorPicker').boundingClientRect(function (rect) {
      _this.setData({
        valueWidthOrHerght: rect.width,
      })
      if (isInit) {
        colorPickerCtx.fillRect(0, 0, rect.width, rect.height);
        util.drawRing(colorPickerCtx, rect.width, rect.height);
        // 设置默认位置
        util.drawSlider(sliderCtx, rect.width, rect.height, 1.0);
        isInit = false;
      }
      _this.setData({
        pickColor: JSON.stringify({
          red: 255,
          green: 0,
          blue: 0
        })
      })
    }).exec();



  },
  observers: {
    'pickColor': function () {
      //颜色发生改变，发送事件父组件
      if (app.globalData.deviceId) {
        this.triggerEvent('pickColor', this.data.pickColor)
      }
    }
  },
  methods: {
    onSlide: function (e) {
      if (!app.globalData.deviceId) {
        wx.showModal({
          title: '提示',
          content: '暂未连接蓝牙设备',
          showCancel: false,
          cancelColor: '#000000',
          confirmText: '确定',
          confirmColor: '#3CC51F'
        });
        return
      }
      let that = this;
      if (e.touches && (e.type === 'touchend')) {
        let x = e.changedTouches[0].x;
        let y = e.changedTouches[0].y;
        if (e.type !== 'touchend') {
          x = e.touches[0].x;
          y = e.touches[0].y;
        }
        //复制画布上指定矩形的像素数据
        wx.canvasGetImageData({
          canvasId: "colorPicker",
          x: x,
          y: y,
          width: 1,
          height: 1,
          success(res) {
            // 转换成hsl格式，获取旋转角度
            let h = util.rgb2hsl(res.data[0], res.data[1], res.data[2]);
            that.setData({
              pickColor: JSON.stringify({
                red: res.data[0],
                green: res.data[1],
                blue: res.data[2]
              })
            })
            // 判断是否在圈内
            if (h[1] !== 1.0) {
              return;
            }
            util.drawSlider(sliderCtx, _this.data.valueWidthOrHerght, _this.data.valueWidthOrHerght, h[0]);
            // 设置设备
            if (e.type !== 'touchEnd') {
              // 触摸结束才设置设备属性
              return;
            }
          }
        }, this);
      }
    },
  }
})